/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"log"
	"os"

	"gitee.com/chuanjinge/go-container/config"
	"gitee.com/chuanjinge/go-container/container"
	"gitee.com/chuanjinge/go-container/pkg"
	"gitee.com/chuanjinge/go-container/pkg/loggers"
	"github.com/spf13/cobra"
)

var _containerId string
var _volume []string

// initCmd represents the init command
var initCmd = &cobra.Command{
	Use:   "init --containerId=xxxx <SHELL-COMMAND>",
	Short: "初始化新进程",
	Long:  `指定<SHELL-COMMAND>作为新的shell的初始命令，比如 /bin/bash`,
	Args: func(cmd *cobra.Command, args []string) error {
		/**
		if len(args) < 1 {
			return fmt.Errorf("请输出初始命令")
		}
		*/
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		logFile, err := setupLogging(config.GlobalConfig().CommonLogPath)
		if err != nil {
			os.Exit(1)
		}
		defer logFile.Close()
		log.Println("init called")
		// 在这里插入调试钩子
		/*
			fmt.Println("Waiting for debugger to attach...")
			sig := make(chan os.Signal, 1)
			signal.Notify(sig, syscall.SIGUSR1)
			<-sig // 等待 SIGUSR1 信号
			fmt.Println("Debugger attached, continuing...")
		*/
		// 执行指定的命令替换掉当前进程
		log.Printf("准备创建容器containerId: %v; volume挂载信息：%v", _containerId, _volume)

		// 初始化日志记录器
		pkg.InitLoggers(_containerId)
		defer func() {
			loggers.CloseAllLogger() // 确保进程结束后关闭日志记录器。
		}()

		// 执行容器中的前台进程
		if err := container.RunReplaceProcess(_containerId, _volume); err != nil {
			log.Fatalf("容器%s运行失败，原因：%s", _containerId, err.Error())
		}
	},
}

func init() {
	initCmd.Flags().StringVarP(&_containerId, "containerId", "c", "", "容器ID")
	initCmd.Flags().StringSliceVarP(&_volume, "volume", "v", nil, "挂载卷共享目录")
	runCmd.MarkFlagRequired("containerId") // 必传参数

	rootCmd.AddCommand(initCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// initCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// initCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
